<template>
  <q-dialog v-model="visible">
    <q-card
      :style="$q.screen.gt.xs ? 'min-width: 50vw;' : 'min-width: 20rem;'"
      :class="ui.cardClass"
    >
      <!-- 名称, 获取当前姿态点信息按钮 -->
      <q-card-section class="row justify-between">
        <div class="text-h6 q-mr-sm row items-center">
          {{
            posture.id
              ? title + posture.name + $t(lang + "姿态点")
              : title + $t(lang + "姿态点")
          }}
        </div>
        <div>
          <q-btn
            no-caps
            class="q-mr-md"
            :class="ui.btnClass"
            icon="precision_manufacturing"
            :label="$t(lang + '获取当前')"
            @click="getNewCurrent.show()"
          />
          <q-btn
            no-caps
            class=""
            color="primary"
            @click="moveToPosture(posture.id)"
            icon="precision_manufacturing"
            v-if="isConnected && posture.id"
            :label="$t(lang + '移动')"
          />
          <!--          <q-btn round flat icon="clear"  v-close-popup />-->
        </div>
      </q-card-section>
      <q-separator :dark="ui.isDark" />
      <q-card-section class="q-gutter-y-sm">
        <q-item-label class="text-subtitle1">{{
          $t(lang + "姿态信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            v-model="posture.name"
            class="col"
            :label="$t(lang + '姿态名称')"
          />
          <q-input
            :dark="ui.isDark"
            dense
            readonly
            outlined
            v-model="posture.frameID"
            class="col"
            :label="$t(lang + '参考坐标')"
          />
          <q-input
            :dark="ui.isDark"
            dense
            readonly
            outlined
            v-model="posture.toolFrameId"
            class="col"
            :label="$t(lang + '参考坐标')"
          />
          <q-input
            :dark="ui.isDark"
            dense
            readonly
            outlined
            v-model="scene.name"
            :label="$t(lang + '场景名称')"
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1">{{
          $t(lang + "类型操作")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-select
            :dark="ui.isDark"
            dense
            :model-value="posture.group"
            use-input
            hide-selected
            fill-input
            input-debounce="0"
            :options="groupOptions"
            @input-value="(val) => (posture.group = val)"
            outlined
            :label="$t(lang + '选择或清空后新增姿态分组')"
            class="col"
          >
            <template v-if="posture.group" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="posture.group = ''"
                class="cursor-pointer"
              />
            </template>
          </q-select>
          <q-select
            :dark="ui.isDark"
            dense
            outlined
            behavior="menu"
            :label="$t(lang + '是否为初始点')"
            v-model="posture.start"
            :options="startOptions"
            class="col"
            emit-value
            map-options
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1">{{
          $t(lang + "位置信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.x"
            class="col"
            label="X"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.y"
            class="col"
            label="Y"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.z"
            class="col"
            label="Z"
          />
        </div>
        <q-separator />
        <q-item-label class="text-subtitle1">{{
          $t(lang + "角度信息")
        }}</q-item-label>
        <div class="row q-gutter-x-sm">
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qx"
            class="col"
            label="X"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qy"
            class="col"
            label="Y"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qz"
            class="col"
            label="Z"
          />
          <q-input
            :dark="ui.isDark"
            dense
            outlined
            type="tel"
            v-model.number="posture.qw"
            class="col"
            label="W"
          />
        </div>
      </q-card-section>
      <!-- 添加 判断有没有modify -->
      <q-card-actions v-if="title === $t(lang + '新增')" align="right">
        <q-btn
          no-caps
          :class="ui.btnClass"
          flat
          :label="$t(lang + '添加姿态')"
          @click="addPosture"
          class="full-width"
        />
      </q-card-actions>
      <!-- 修改删除 -->
      <q-card-actions v-else align="right" class="row">
        <q-btn
          no-caps
          flat
          :label="$t(lang + '删除姿态')"
          @click="delPosture"
          class="col bg-red-5 text-white text-space text-bold"
        />
        <q-btn
          no-caps
          :class="ui.btnClass"
          flat
          :label="$t(lang + '修改姿态')"
          @click="modifyPosture"
          class="col"
        />
      </q-card-actions>

      <q-inner-loading
        :showing="loading"
        :label="$t(lang + '获取当前姿态')"
        label-class="text-teal"
        label-style="font-size: 1.1rem"
      />

      <now-posture ref="getNewCurrent" @getPosture="getPosture" />
    </q-card>
  </q-dialog>
</template>

<script setup>
import { ref } from "vue";
import { api } from "boot/axios";
import { useAPIStore } from "stores/api";
import { useFunctionsStore } from "stores/functions";
import { storeToRefs } from "pinia";
import { useQuasar } from "quasar";
import NowPosture from "components/posture/GetPosture.vue";
import { useUiStore } from "stores/ui";
import { useI18n } from "vue-i18n";
import { isConnected } from "src/utils/deviceWs";

const t = useI18n().t;
const lang = "routeManage.PosturePoint.";
const $q = useQuasar();
const ui = useUiStore();
const { scene } = storeToRefs(useFunctionsStore()); //  当前场景
const visible = ref(false); // 弹框显示
const loading = ref(false); // loading效果
const getNewCurrent = ref();
const posture = ref({}); // 当前姿态点信息
const title = ref(t(lang + "新增"));
const groupOptions = ref([]); // 姿态分组列表
const startOptions = ref([
  { value: true, label: t("yes") },
  { value: false, label: t("no") },
]);
const emit = defineEmits(["refresh"]);
defineExpose({ show });

// 显示
function show(posture) {
  // 显示添加弹框
  visible.value = true;
  loading.value = false;
  // 获取分组列表
  getGroupList();
  // 新增或修改弹窗
  showDialog(posture);
}

// 获取分组列表
function getGroupList() {
  const params = {
    scenario: scene.value.id,
    type: "normal",
  };
  api
    .get(useAPIStore().postureUrl + "new/posture/groups", { params })
    .then((rs) => {
      if (rs.data.code !== 200)
        return $q.notify({
          message: t(lang + "分组列表获取失败"),
          type: "negative",
        });
      groupOptions.value = rs.data.data;
    })
    .catch(() => {
      $q.notify({ message: t(lang + "分组列表获取异常"), type: "negative" });
    });
}

// 修改姿态弹窗
function showDialog(data) {
  if (data) {
    posture.value = JSON.parse(JSON.stringify(data));
    title.value = t(lang + "修改");
  } else {
    posture.value = {};
    posture.value.start = false;
    getPosture();
    title.value = t(lang + "新增");
  }
}

// 获取当前姿态
function getPosture(targetFrame, sourceFrame) {
  loading.value = true;
  // 获取当前姿态点信息
  api
    .post(
      useAPIStore().amrUrl + "ros/call",
      {
        target_frame: targetFrame || "arm_base",
        source_frame: sourceFrame || "flange",
      },
      { params: { service: "tf/get_frame_pose" } }
    )
    .then((res) => {
      const pose = res.data.values.pose;
      posture.value.seq = pose.header.seq;
      posture.value.frameID = pose.header.frame_id;
      posture.value.toolFrameId = sourceFrame || "flange";
      posture.value.qw = pose.pose.orientation.w;
      posture.value.qx = pose.pose.orientation.x;
      posture.value.qy = pose.pose.orientation.y;
      posture.value.qz = pose.pose.orientation.z;
      posture.value.x = pose.pose.position.x;
      posture.value.y = pose.pose.position.y;
      posture.value.z = pose.pose.position.z;

      // 关闭loading
      loading.value = false;
    })
    .catch(() => {
      $q.notify({
        type: "negative",
        message: t(lang + "获取当前姿态失败请稍后添加"),
      });
      loading.value = false;
      $q.dialog({
        dark: ui.isDark,
        title: t(lang + "获取姿态失败请检查机械臂是否正常"),
        ok: t("know"),
        cancel: false,
      }).onOk(() => {
        visible.value = false;
      });
    });
}
// 新增
function addPosture() {
  // 判断不为空
  if (!posture.value.name) {
    $q.notify({ type: "negative", message: t(lang + "请填写姿态名称") });
    return;
  }
  posture.value.type = "normal";
  posture.value.scenario = scene.value.id;
  if (posture.value.start) {
    $q.dialog({
      dark: ui.isDark,
      title: t(lang + "再次确认起始点位置是否正确"),
      message: `x: ${posture.value.x}，y: ${posture.value.y}`,
      cancel: t("cancel"),
      ok: t("ok"),
    }).onOk(() => {
      api
        .post(useAPIStore().postureUrl + "/new/posture", posture.value)
        .then((rs) => {
          if (rs.data.code !== 200)
            return $q.notify({
              message: t(lang + "添加失败"),
              type: "negative",
            });
          visible.value = false;
          emit("refresh", "create", rs.data.data);
          $q.notify({ message: t(lang + "添加成功"), type: "positive" });
        })
        .catch(() => {
          $q.notify({
            message: t(lang + "添加失败请稍后再试"),
            type: "negative",
          });
        });
    });
  } else {
    api
      .post(useAPIStore().postureUrl + "/new/posture", posture.value)
      .then((rs) => {
        if (rs.data.code !== 200)
          return $q.notify({ message: t(lang + "添加失败"), type: "negative" });
        visible.value = false;
        emit("refresh", "create", rs.data.data);
        $q.notify({ message: t(lang + "添加成功"), type: "positive" });
      })
      .catch(() => {
        $q.notify({
          message: t(lang + "添加失败请稍后再试"),
          type: "negative",
        });
      });
  }
}

// 修改
function modifyPosture() {
  // 判断不为空
  if (!posture.value.name.trim()) {
    $q.notify({ type: "negative", message: t(lang + "text22") });
    return;
  }
  api
    .put(useAPIStore().postureUrl + "/new/posture", posture.value)
    .then((rs) => {
      if (rs.data.code === 200) {
        visible.value = false;
        emit("refresh", "modify", rs.data.data);
        $q.notify({ message: t(lang + "修改成功"), type: "positive" });
      } else {
        $q.notify({ message: t(lang + "修改失败"), type: "negative" });
      }
    })
    .catch(() => {
      $q.notify({ message: t(lang + "修改异常请稍后再试"), type: "negative" });
    });
}

// 删除
function delPosture() {
  $q.dialog({
    dark: ui.isDark,
    title: `${t(lang + "确定要删除姿态点")} ${posture.value.name}`,
    ok: t("ok"),
    cancel: t("cancel"),
  }).onOk(() => {
    api
      .delete(useAPIStore().postureUrl + "/new/posture/" + posture.value.id)
      .then((rs) => {
        if (rs.data.code !== 200)
          return $q.notify({ message: t(lang + "删除失败"), type: "negative" });
        visible.value = false;
        emit("refresh", "delete", rs.data.data);
        $q.notify({ message: t(lang + "删除成功"), type: "positive" });
        emit("refresh");
      })
      .catch(() => {
        $q.notify({
          message: t(lang + "删除失败请稍后再试"),
          type: "negative",
        });
      });
  });
}
// 当前姿态移动
function moveToPosture(id) {
  $q.dialog({
    title: "移动",
    message: "请选择移动类型",
    options: {
      type: "radio",
      model: "joint",
      // inline: true
      items: [
        { label: "关节", value: "joint" },
        { label: "直线", value: "linear" },
      ],
    },
    cancel: t("cancel"),
    ok: t("ok"),
    persistent: true,
  }).onOk((data) => {
    api
      .get(useAPIStore().amrUrl + "amr/add", {
        params: { type: "posture", content: id + "," + data },
      })
      .then((rs) => {
        if (rs.data === "done") {
          $q.notify({
            type: "positive",
            message: t(lang + "指令已下发"),
            position: "bottom",
          });
        }
      })
      .catch(() => {
        $q.notify({
          type: "negative",
          message: t(lang + "接口调用出现错误"),
          position: "bottom",
        });
      });
  });
}
</script>

<style scoped></style>
